<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/26
 * Time: 16:09
 */
namespace app\admin\controller;

use app\admin\model\OrderModel;
use app\admin\controller\Product;
use app\admin\model\MemberModel;
use think\Db;


class Order extends Base
{
    /**
     * 添加订单
     * Array
     */
    public function orderAdd (){
        $order = new OrderModel();
        if (request()->isPost()){
            $param = input('post.');
            if (empty($param['order_id'])) {
                return $this->addNewOrder($param,$order);// 新订单录入
            }else{
                return $this->addOldOrder($param,$order);// 旧订单追加
            }
        }
    }

		// 追加流水修改订单价格
		public function appendAccChangeOrder($param,$order){
			$param['registration'] = $param['registration'] == '' ? 0 : $param['registration'];
			$param['material_cost'] = $param['material_cost'] == '' ? 0 : $param['material_cost'];
			$param['photo_collection'] = $param['photo_collection'] == '' ? 0 : $param['photo_collection'];
			$param['tuition'] = $param['tuition'] == '' ? 0 : $param['tuition'];
			$total_amount = $param['registration'] + $param['material_cost'] + $param['photo_collection'] + $param['tuition'];
			// print_r($total_amount);
			if($total_amount == 0 || $total_amount == ''){
					return msg(-1, '', '不能全部费用为空!');
			}
			$accData = [
					'order_sn' => $order['order_sn'],//关联单号
					'm_id' => $order['m_id'],//客户ID
					's_id' => 0,//关联人id
					'total_amount' => $total_amount,
					'status' => 0, //流水状态
					'c_time' => time(),//创建时间
					'finish_time' => strtotime('+1 day'),//完成时间
					'create_uid' => $order['create_uid'],//创建者id
					'agent' => session('id'),//经办人id
					'remarks' => $order['remarks'],//备注
					'registration' => $param['registration'],//报名费
					'material_cost' => $param['material_cost'],//资料费
					'photo_collection' => $param['photo_collection'],//照片费
					'tuition' => $param['tuition'],
			];
			$orderData = [
				'registration' => $order['registration'] + $param['registration'],
				'tuition' => $order['tuition'] + $param['tuition'],
				'material_cost' => $order['material_cost'] + $param['material_cost'],
				'photo_collection' => $order['photo_collection'] + $param['photo_collection'],
			];
			$orderData['total_amount'] = 0;
			foreach($orderData as $v){
				$orderData['total_amount'] += $v;
			}
			DB::startTrans();
			try{
				$result = Db::name('account')->insertGetId($accData);
				$account_sn = date("Ymd").$result;
				DB::name('account')->where('id',$result)->update(['account_sn'=>$account_sn]);
				DB::name('order')->where('id',$param['order_id'])->update($orderData);
				DB::commit();
				return msg(1, '', '追加成功');
			}catch(\Exception $e){
				DB::rollback();
				return msg(-1, '', '追加失败,'.$e->getMessage());
			}
		}

    //旧订单录入OR修改
  	public function addOldOrder($param,$order){

      // print_r($param);die;
  		$orderInfo = DB::name('order')->where('id',$param['order_id'])->find();
			if(isset($param['is_append'])){
					unset($param['is_append']);
					return $this->appendAccChangeOrder($param,$orderInfo);
			}
      // 检测订单状态

      if($orderInfo['status'] != 4){
					if($param['tuition'] == 0 && $param['photo_collection'] == 0 && $param['material_cost'] == 0 && $param['registration'] == 0){
							return msg(-1,'','已确定订单,不可更改');
					}
      }
      // 判断产品是否发生改变
      if(isset($param['school_id']) && isset($param['major_id'])){
          if($orderInfo['school_id'] != $param['school_id'] || $orderInfo['major_id'] != $param['major_id'] || $orderInfo['pro_id'] != $param['name']){
              if($orderInfo['pro_id'] != $param['name'] && !empty($param['name'])){
                  if(!isset($param['cofigArr'])){
                      return msg(-1, '', '请选择产品配置');
                  }else {
                      $cofigArr = $param['cofigArr'];
                      $pid = $this->postOrderCfg($cofigArr);
                      $param['grade'] = $pid[1];
                      $param['system'] = $pid[2];
                      $param['payment_method'] = $pid[3];
                      $param['acquisition_mode'] = $pid[4];
                      $param['attr_info'] = $param['cofigArr'];//产品属性信息
                  }
              }else{
                  return msg(-1, '', '请选择产品');
              }
              $param['status'] = 4;//设置订单状态为创建中
              $param['pro_id'] = $param['name'];//产品ID
              $param['stu_name'] = $param['stu_name'];//客户名称
              $param['batch'] = $param['batch'];//批次
              $param['agent'] = $param['relation_id']; //经办人ID
              $tuition = $param['tuition'] == 0 ? $orderInfo['tuition'] : $param['tuition'];//学费
              $photo_collection = $param['photo_collection'] == 0 ? $orderInfo['photo_collection'] : $param['photo_collection'];//照片采集费
              $material_cost = $param['material_cost'] == 0 ? $orderInfo['material_cost'] : $param['material_cost'];//材料费
              $registration = $param['registration'] == 0 ? $orderInfo['registration'] : $param['registration'];//报名费
              $param['total_amount'] = $tuition + $photo_collection + $material_cost + $registration;//总金额
          }else {
              $param['pro_id'] = $param['name'];//产品ID
              $param['attr_info'] = $orderInfo['attr_info'];//产品属性信息
              $param['payment_method'] = $orderInfo['payment_method'];//缴费方式(全额/三期/六期等)
              $param['status'] = 4;//修改订单状态为创建中
							$tuition = $param['tuition'] == 0 ? $orderInfo['tuition'] : $param['tuition'];//学费
              $photo_collection = $param['photo_collection'] == 0 ? $orderInfo['photo_collection'] : $param['photo_collection'];//照片采集费
              $material_cost = $param['material_cost'] == 0 ? $orderInfo['material_cost'] : $param['material_cost'];//材料费
              $registration = $param['registration'] == 0 ? $orderInfo['registration'] : $param['registration'];//报名费
              $param['total_amount'] = $tuition + $photo_collection + $material_cost + $registration;//总金额
          }
      }else{
          //验证测试[确认订单]
          $param['school'] = $orderInfo['school'];
          $param['major'] = $orderInfo['major'];
          $param['pay_type'] = $orderInfo['pay_type'];
          $param['attr_info'] = $orderInfo['attr_info'];//产品属性信息
          $param['stu_name'] = $orderInfo['stu_name'];//客户名称

          $param['status'] = 1;//修改订单状态为进行中
          $param['m_id'] = $orderInfo['m_id'];
          $param['order_sn'] = $orderInfo['order_sn'];//订单号
          $param['payment_method'] = $orderInfo['payment_method'];//缴费方式(全额/三期/六期等)
          $param['pro_id'] = $orderInfo['pro_id'];//产品ID
          $param['batch'] = $orderInfo['batch'];//批次
      		$param['agent'] = session('id'); //经办人ID
          $param['create_uid'] = $orderInfo['create_uid'];; //创建者ID
          $param['remarks'] = $orderInfo['remarks'];; //订单备注
          if(isset($param['tuition']) || isset($param['photo_collection']) || isset($param['material_cost']) || isset($param['registration'])){
              $tuition = $param['tuition'] == 0 ? $orderInfo['tuition'] : $param['tuition'] + $orderInfo['tuition'];//学费
              $photo_collection = $param['photo_collection'] == 0 ? $orderInfo['photo_collection'] : $param['photo_collection'] + $orderInfo['photo_collection'];//照片采集费
              $material_cost = $param['material_cost'] == 0 ? $orderInfo['material_cost'] : $param['material_cost'] + $orderInfo['material_cost'];//材料费
              $registration = $param['registration'] == 0 ? $orderInfo['registration'] : $param['registration'] + $orderInfo['registration'];//报名费
              $param['total_amount'] = $tuition + $photo_collection + $material_cost + $registration;//总金额
          }else{
              $param['tuition'] = $orderInfo['tuition'];//学费
              $param['photo_collection'] = $orderInfo['photo_collection'] ;//照片采集费
              $param['material_cost'] = $orderInfo['material_cost'];//材料费
              $param['registration'] = $orderInfo['registration'];//报名费
              $param['total_amount'] = $param['tuition'] + $param['photo_collection'] + $param['material_cost'] + $param['registration'];//总金额
          }
      }
  		$param['c_time'] = time();//创建时间

      // print_r($param);die;
			$result = $this->validate($param,'OrderValidate');

			if($result === true){
				$flag = $order->getOrderAdd($param);
			}else{
				return json(msg(-1,'',$result));
			}
			return json(msg($flag['code'], $flag['data'], $flag['msg']));
  	}
    //新订单录入
    public function addNewOrder($param,$order){
        if(!isset($param['name'])){
            return msg(-1, '', '请选择产品');
        }
        if(!isset($param['cofigArr'])){
            return msg(-1, '', '请选择产品配置');
        }else{
            $cofigArr = $param['cofigArr'];
        }
        if(!$param['relation_id']){
             return msg(-1, '', '请选择咨询师');
        }
        if(empty($param['pay_type'])){
             return msg(-1, '', '请选择支付方式');
        }
        $pid = $this->postOrderCfg($cofigArr);

        $param['grade'] = $pid[1];
        $param['system'] = $pid[2];
        $param['payment_method'] = $pid[3];
        $param['acquisition_mode'] = $pid[4];
        $param['registration'] = empty($param['registration']) ? 0 : $param['registration'];
        $param['material_cost'] = empty($param['material_cost']) ? 0 : $param['material_cost'];
        $param['photo_collection'] = empty($param['photo_collection']) ? 0 : $param['photo_collection'];
        $param['tuition'] = empty($param['tuition']) ? 0 : $param['tuition'];
        $param['total_amount'] = $param['registration'] + $param['material_cost'] + $param['photo_collection'] + $param['tuition'];//总金额

        $order_sn = date('Ymd',time()).rand(10000, 99999);
        $agent = session('id');
        $param['pro_id'] = (int)$param['name'];//订单来源
        $param['source'] = 0;//订单来源
        $param['order_sn'] = $order_sn;//收据号(订单号)
        $param['status'] = 4; //订单状态 [创建中]
        $param['c_time'] = time(); //创建时间
        $param['consultant'] = $param['relation_id']; //所属咨询师
        $param['create_uid'] = $param['relation_id']; //创建人ID
		    $param['agent'] = $param['relation_id']; //经办人ID
        $param['attr_info'] = $param['cofigArr']; //产品属性信息

        //修改客户信息($where)AND添加客户信息
        if(isset($param['m_id'])){
            $flag = $order->getOrderAdd($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }else{
            $where = [];
            $where['name'] = $param['stu_name'];
            $where['phone'] = $param['phone'];
            $where['qq'] = $param['qq'];
            $where['weixin'] = $param['weixin'];
            $where['adress'] = $param['adress'];
            $where['remarks'] = $param['remarks'];

            $where['status'] = 6;//状态
            $where['grade'] = 2;//等级
            $where['nation'] = $param['nation'];//民族
            $where['id_card'] = $param['id_card'];//身份证号
            $where['birthday'] = $param['birthday'];//生　　日
            $where['sex'] = $param['sex'];//性　　别
            $where['education'] = $param['education'];//学历
            $where['intention'] = $param['intention'];//意向专业
            $where['industry'] = $param['industry'];//工作行业
            $where['region'] = $param['region'];//所在地区
            $where['graduate_school'] = $param['graduate_school'];//毕业学校
            $where['certificate_number'] = $param['certificate_number'];//证书编号
            $where['graduation_time'] = $param['graduation_time'];//毕业时间
            $where['source_origin'] = $param['source_origin'];//生源途径

            $where['create_uid'] = $param['relation_id'];//创建者id
            //录入信息
            $where['first_relation'] = $param['relation_id'];//关联人
            $where['entry_time'] = time();//时间
            $memberModel = new MemberModel;
            $memberId = $memberModel->addMember($where);
            $param['m_id'] = $memberId;
            $flag = $order->getOrderAdd($param);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
    }

    public function postOrderCfg($cofigArr){
        $attr_arr = explode(",",explode("^",$cofigArr)[0]);

        $price = explode("price:",$attr_arr[sizeof($attr_arr)-1])[1];
        unset($attr_arr[sizeof($attr_arr)-1]);
        $pid = [];
        foreach($attr_arr as $k => $v){
            $pid[explode('-',$v)[0]] = explode('-',$v)[1];
        }
        $pid['price'] =  $price;
        return $pid;
    }
    /**
     * Ajax 查询产品列表
     */
    public function productList()
    {
        if (request()->isAjax()){
            $param = input('param.');
            $school_id = $param['school_id'];
            $major_id = $param['major_id'];
            $order = new OrderModel();
            $proName = $order->getProductList($school_id,$major_id);
            return json($proName);
        }
    }
    /**
     * Ajax 查询产品配置
     */
    public function configList()
    {
        if (request()->isAjax()){
            $param = input('param.');
            $id = $param['product_id'];
            $order = new OrderModel();
            $cofigArr = $order->getConfigList($id);
            return ['code'=>1,'data'=>$cofigArr];
        }
    }
    /**
     * Ajax 查询产品详情
     * id->order_id
     */
    public function productInfo(){
        $order_id = input('post.id');
        $orderNodel = new OrderModel();
        $proInfo = $orderNodel->getProductInfo($order_id);
        return ['code'=>1,'data'=>$proInfo];
    }
}
